# Sihe Think Tank - Frontend Startup Script

# Keep window open even if script fails
$ErrorActionPreference = "Continue"

Write-Host "==================================" -ForegroundColor Cyan
Write-Host "  Sihe Think Tank - Frontend" -ForegroundColor Cyan
Write-Host "==================================" -ForegroundColor Cyan
Write-Host ""

# Set console encoding to UTF-8
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$OutputEncoding = [System.Text.Encoding]::UTF8
chcp 65001 | Out-Null

Write-Host "[OK] UTF-8 encoding configured" -ForegroundColor Green

# Check and clean port 3300
Write-Host "[CHECK] Checking port 3300..." -ForegroundColor Yellow
$port = 3300
$connections = Get-NetTCPConnection -LocalPort $port -ErrorAction SilentlyContinue

if ($connections) {
    Write-Host "[WARN] Port 3300 is occupied!" -ForegroundColor Red
    Write-Host "[ACTION] Cleaning up Node.js processes on port 3300..." -ForegroundColor Yellow
    
    $connections | ForEach-Object {
        $pid = $_.OwningProcess
        try {
            $processName = (Get-Process -Id $pid -ErrorAction SilentlyContinue).ProcessName
            Stop-Process -Id $pid -Force -ErrorAction Stop
            Write-Host "[OK] Terminated process: $processName (PID: $pid)" -ForegroundColor Green
        } catch {
            Write-Host "[WARN] Could not terminate PID: $pid" -ForegroundColor Yellow
        }
    }
    
    Write-Host "[WAIT] Waiting for port to be released..." -ForegroundColor Yellow
    Start-Sleep -Seconds 3
    Write-Host "[OK] Port 3300 should now be available" -ForegroundColor Green
} else {
    Write-Host "[OK] Port 3300 is available" -ForegroundColor Green
}

Write-Host ""

# Get script directory and enter frontend directory
$scriptPath = $MyInvocation.MyCommand.Path
$scriptDir = Split-Path -Parent $scriptPath
$frontendDir = Join-Path $scriptDir "frontend"

Write-Host "[INFO] Frontend directory: $frontendDir" -ForegroundColor Cyan

# Check if frontend directory exists
if (-not (Test-Path $frontendDir)) {
    Write-Host "[ERROR] Frontend directory not found: $frontendDir" -ForegroundColor Red
    Write-Host ""
    Write-Host "Press any key to exit..." -ForegroundColor Yellow
    $null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
    exit 1
}

Set-Location -Path $frontendDir
Write-Host "[OK] Changed to frontend directory" -ForegroundColor Green

# Check if node_modules exists
if (-not (Test-Path ".\node_modules")) {
    Write-Host "[WARN] node_modules not found!" -ForegroundColor Yellow
    Write-Host "[INFO] Please run: npm install" -ForegroundColor Cyan
}

Write-Host ""
Write-Host "========================================" -ForegroundColor Green
Write-Host "  Starting Frontend Service..." -ForegroundColor Green
Write-Host "  Press Ctrl+C to stop" -ForegroundColor Yellow
Write-Host "========================================" -ForegroundColor Green
Write-Host ""

# Start frontend service with error handling
Write-Host "[START] Launching npm run dev..." -ForegroundColor Cyan
try {
    & npm run dev
    $exitCode = $LASTEXITCODE
    if ($exitCode -ne 0 -and $exitCode -ne $null) {
        Write-Host ""
        Write-Host "[ERROR] Frontend service failed to start! Exit code: $exitCode" -ForegroundColor Red
        Write-Host ""
        Write-Host "Common issues:" -ForegroundColor Yellow
        Write-Host "  1. Port 3300 is still occupied" -ForegroundColor Yellow
        Write-Host "  2. node_modules not installed (run: npm install)" -ForegroundColor Yellow
        Write-Host "  3. Node.js version incompatible" -ForegroundColor Yellow
        Write-Host ""
    }
} catch {
    Write-Host ""
    Write-Host "[ERROR] Frontend service failed to start!" -ForegroundColor Red
    Write-Host "Error: $_" -ForegroundColor Red
    Write-Host ""
}

# If we get here, the service stopped
Write-Host ""
Write-Host "[INFO] Frontend service stopped" -ForegroundColor Yellow
Write-Host ""
Write-Host "Press any key to exit..." -ForegroundColor Yellow
$null = $Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
